<?php
	include ("../DatabaseConnectionInformation.php");

	$username = $_POST["user"];
	$currInterlocutor = $_POST["interlocutor"];
	$c=0;
   	$dbh = mysql_connect($host, $user, $pswd) or die("Cannot connect to MySQL.");
   	mysql_select_db($database) or die("Cannot connect to database.");
	$r=mysql_query ("SELECT `user`.`nickName`, `user`.`login` FROM `friends`,`user` WHERE `friends`.`who`='$username' AND `user`.`login`=`friends`.`whom`;");
	?>
	<form id="changeInterlocutor" action="chat.php" method="POST">
	<input id="interlocutorLogin" name="interlocutor" type="hidden" value="TEST!">
	<input id="prevInterlocutorLogin" name="prevInterlocutorLogin" type="hidden" value="<?php echo $currInterlocutor; ?>">
	<?php
	while ($row=mysql_fetch_array($r))
	{
			if ($row["login"] != $currInterlocutor)
			{
				$smbd = $row["login"];
				$resN=mysql_query ("SELECT COUNT(*) AS `numOfUnreadMessages` FROM `history`, `friends` WHERE `history`.`sender` = `friends`.`whom` AND `history`.`receiver` = `friends`.`who` AND `history`.`time` > `friends`.`lastRead` AND `friends`.`who` = '$username' AND `friends`.`whom` = '$smbd';") or die("Invalid query: " . mysql_error());
				$rowWithCount = mysql_fetch_array($resN);
				$N = $rowWithCount["numOfUnreadMessages"];
			}
			else
				$N=0;
			?>
			<a href="chat.php" title="<?php echo $row["login"]; ?>" class="link" onclick="send(this);return(false)">
			<?php echo $row["nickName"];?> <?php
			if ($N!=0)
				echo "($N)";
			?>
			</a><br>
			<?php
		$c++;
	}
	mysql_close($dbh);
	?>
	</form>
	<script type="text/javascript">
	function send( ptr_ )
	{
		var collocutorLogin = document.getElementById('interlocutorLogin')
		with ( document.getElementById('changeInterlocutor') )
		{
		  collocutorLogin.value=ptr_.title
		  submit()
		}
	}
	</script>
	<?php
	if ($c==0) // если ни одной записи не встретилось
		echo "Empty friend list!<br>";
?>
